"use client";

import { useDownloadStaticHelp } from "@/service/dowload";
import { baseURL } from "@/service/request/config";
import CloudUploadIcon from "@mui/icons-material/CloudDownload";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Container from "@mui/material/Container";
import Paper from "@mui/material/Paper";
import { styled } from "@mui/material/styles";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import type { DescriptionsProps } from "antd";
import { Descriptions, message, Rate } from "antd";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import p1 from "../../../public/help1.jpg";
import p2 from "../../../public/help2.jpg";
import p3 from "../../../public/help3.jpg";
import p4 from "../../../public/help4.jpg";
import HelpH1 from "../components/HelpH1";
import HelpH2 from "../components/HelpH2";
import HelpH3 from "../components/HelpH3";
import HelpParagraph from "../components/HelpParagrash";
import HelpParagraphIndent from "../components/HelpParagrashIndent";
import HelpStack from "../components/HelpStack";
import HelpStackIndent from "../components/HelpStackIndent";
import ImgContainer from "../components/ImgContainer";

const StyledTableCell = styled(TableCell)(({ theme }) => ({
  [`&.${tableCellClasses.head}`]: {
    backgroundColor: "rgb(245, 246, 249)",
    color: theme.palette.common.black,
  },
  [`&.${tableCellClasses.body}`]: {
    fontSize: 14,
  },
}));

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  "&:nth-of-type(odd)": {
    backgroundColor: theme.palette.common.white,
  },
  // hide last border
  "&:last-child td, &:last-child th": {
    border: 0,
  },
}));

function createData(
  soft: string,
  colName: string,
  description: string,
  key: string
) {
  return { soft, colName, description, key };
}

const rows = [
  createData(
    "DRAM",
    "rank",
    "For each gene annotated, DRAM provides a single, summary rank (A–E), which represents the confidence of the annotation",
    "1"
  ),
  createData(
    "DRAM",
    "kegg_hit",
    "The result output by DRAM is the match between the sequence and the KEGG database.",
    "2"
  ),
  createData("DRAM", "EC.x", "DRAM annotated Enzyme Commission number", "3"),
  createData(
    "DRAM",
    "uniref_identity",
    "The result output by DRAM is the match between the sequence and the uniref database.",
    "4"
  ),
  createData(
    "DRAM",
    "uniref_bitScore",
    "The result output by DRAM is the match between the sequence and the uniref database.",
    "5"
  ),
  createData(
    "DRAM",
    "uniref_eval",
    "The result output by DRAM is the match between the sequence and the uniref database.",
    "6"
  ),
  createData(
    "DRAM",
    "cazy_hits",
    "The result output by DRAM is the match between the sequence and the CAZY database.",
    "7"
  ),
  createData(
    "microbeannotator",
    "Kofam",
    "All proteins are searched against the curated KEGG Ortholog (KO) database using Kofamscan",
    "8"
  ),
  createData(
    "microbeannotator",
    "refseq",
    "Proteins without a KO identifier (or match in Swissprot) are extracted and searched against the curated RefSeq database.",
    "9"
  ),
  createData(
    "microbeannotator",
    "refseq",
    "Proteins without a KO identifier (or match in Swissprot) are extracted and searched against the curated RefSeq database.",
    "10"
  ),
  createData("eggnog-mapper", "evalue", "/", "11"),
  createData("eggnog-mapper", "score", "/", "12"),
  createData(
    "eggnog-mapper",
    "COG_category",
    "COG category of the narrowest OG with a valid one.",
    "13"
  ),
  createData(
    "eggnog-mapper",
    "Description",
    "Description of the narrowest OG with a valid one.",
    "14"
  ),
  createData(
    "eggnog-mapper",
    "EC.y",
    "eggnog annotated Enzyme Commission number",
    "15"
  ),
];

function CustomizedTables() {
  return (
    <TableContainer
      component={Paper}
      style={{ borderRadius: "12px" }}
      className="item_container"
    >
      <Table sx={{ minWidth: 700 }} aria-label="customized table">
        <TableHead>
          <TableRow>
            <StyledTableCell>soft</StyledTableCell>
            <StyledTableCell align="left">col name</StyledTableCell>
            <StyledTableCell align="left">Description</StyledTableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row) => (
            <StyledTableRow key={row.key}>
              <StyledTableCell component="th" scope="row">
                {row.soft}
              </StyledTableCell>
              <StyledTableCell align="left">{row.colName}</StyledTableCell>
              <StyledTableCell align="left">{row.description}</StyledTableCell>
            </StyledTableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}

const items: DescriptionsProps["items"] = [
  {
    key: "0",
    label: (
      <span
        style={{ fontWeight: "bold", color: "black", whiteSpace: "nowrap" }}
      >
        Folder/File name
      </span>
    ),
    children: <span style={{ fontWeight: "bold" }}>Description</span>,
  },
  {
    key: "1",
    label: (
      <span
        style={{ fontWeight: "bold", color: "black", whiteSpace: "nowrap" }}
      >
        best_hit_models/
      </span>
    ),
    children:
      "This folder contains top 20 most similar protein structures (both TM-score > 0.5 to the template; stored in .gz format) as well as the superposed structure images of the top 20 (stored in .png format).",
  },
  {
    key: "2",
    label: (
      <span
        style={{ fontWeight: "bold", color: "black", whiteSpace: "nowrap" }}
      >
        3rbf_A.fasta
      </span>
    ),
    children:
      "Protein sequence of the template structure uploaded by the user.",
  },
  {
    key: "3",
    label: (
      <span
        style={{ fontWeight: "bold", color: "black", whiteSpace: "nowrap" }}
      >
        3rbf_A.pdb
      </span>
    ),
    children: "Template protein structure uploaded by the user.",
  },
  {
    key: "4",
    label: (
      <span
        style={{ fontWeight: "bold", color: "black", whiteSpace: "nowrap" }}
      >
        usalign_hits.csv
      </span>
    ),
    children:
      "Structure similarity results (US-align) for all similar structures. It also includes the sequence similarity (BLASTp) results of the top 20 proteins.",
  },
  {
    key: "5",
    label: (
      <span
        style={{ fontWeight: "bold", color: "black", whiteSpace: "nowrap" }}
      >
        hits.fasta
      </span>
    ),
    children: "All protein sequences of the similar structures.",
  },
  {
    key: "6",
    label: (
      <span
        style={{ fontWeight: "bold", color: "black", whiteSpace: "nowrap" }}
      >
        top.fasta
      </span>
    ),
    children: "Protein sequences of the top 20 similar structures.",
  },
  {
    key: "7",
    label: (
      <span
        style={{ fontWeight: "bold", color: "black", whiteSpace: "nowrap" }}
      >
        top_hits.ali
      </span>
    ),
    children:
      "Detailed result of the sequence alignment (BLASTp) between the top 20 ranked proteins and the template protein.",
  },
  {
    key: "8",
    label: (
      <span
        style={{ fontWeight: "bold", color: "black", whiteSpace: "nowrap" }}
      >
        annotation.csv
      </span>
    ),
    children: (
      <div>
        Information of all the similar proteins. The annotation.csv is extract
        from the Metadata of GMPS protein structures. For better understanding,
        please refer to the detailed explanation of the metadata below.
      </div>
    ),
  },
];

const item1s: DescriptionsProps["items"] = [
  {
    key: "1",
    label: <span style={{ color: "black", fontWeight: "bold" }}>genome/</span>,
    children:
      "Folder contains the genome of this species used to build the GMPS protein structures.",
  },
  {
    key: "2",
    label: <span style={{ color: "black", fontWeight: "bold" }}>pdb/</span>,
    children:
      "Folder contains all protein structures of the species available in the GMPS database.",
  },
  {
    key: "3",
    label: <span style={{ color: "black", fontWeight: "bold" }}>protein/</span>,
    children:
      "Folder contains the protein sequences derived from the species' genome.",
  },
  {
    key: "4",
    label: (
      <span style={{ color: "black", fontWeight: "bold" }}>
        Bifidobacterium_adolescentis.csv
      </span>
    ),
    children: (
      <span>
        Metadata table for the proteins of{" "}
        <span style={{ fontStyle: "oblique" }}>
          Bifidobacterium adolescentis
        </span>
        , including most similar UniProt protein accession, functional
        annotations.
      </span>
    ),
  },
];

const item2s: DescriptionsProps["items"] = [
  {
    key: "1",
    label: <span style={{ color: "black", fontWeight: "bold" }}>genome/</span>,
    children: (
      <span>
        Folder contains the genomes of all phages in GMPS that use this bacteria
        species(e.g.{" "}
        <span style={{ fontStyle: "oblique" }}>
          Bifidobacterium adolescentis
        </span>
        ) as their host. One fasta file is one isolated phage genome from the
        GPIC (for phage) or one predicted prophage genome (for prophage).
      </span>
    ),
  },
  {
    key: "2",
    label: <span style={{ color: "black", fontWeight: "bold" }}>pdb/</span>,
    children: (
      <span>
        Folder contains the protein structures of all phages in GMPS that use
        this bacteria species (e.g.{" "}
        <span style={{ fontStyle: "oblique" }}>
          Bifidobacterium adolescentis
        </span>
        ) as their host.
      </span>
    ),
  },
  {
    key: "3",
    label: <span style={{ color: "black", fontWeight: "bold" }}>protein/</span>,
    children: (
      <span>
        Folder contains the protein sequences derived from the phage genomes.
      </span>
    ),
  },
  {
    key: "4",
    label: (
      <span style={{ color: "black", fontWeight: "bold" }}>
        Bifidobacterium_adolescentis.csv
      </span>
    ),
    children: (
      <span>
        This file contains the corresponding information for the proteins of all
        phages in GMPS that use this bacteria species(e.g.{" "}
        <span style={{ fontStyle: "oblique" }}>
          Bifidobacterium adolescentis
        </span>
        ) as their host.
      </span>
    ),
  },
];

export default function Help() {
  const router = useRouter();
  function isInViewPortOfOne(element: Element) {
    const screenHeight =
      window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight;
    const top =
      element.getBoundingClientRect() && element.getBoundingClientRect().top;

    return top <= screenHeight;
  }

  const { mutateAsync: downFile, isPending: downloadPending } =
    useDownloadStaticHelp();

  const handleDownloadHelpFile = async (filename: string) => {
    try {
      const link = document.createElement("a");
      link.target = "_self";
      link.href = `${baseURL}/download_file/static/?filename=${filename}`;
      link.click();
      link.remove();
    } catch (err: any) {
      message.error("该文件不存在");
    } finally {
    }
  };

  const checkScrollHeightAndLoadAnimation = () => {
    let elements = document.querySelectorAll(".item_container");

    if (elements && elements.length > 0) {
      elements.forEach((ele) => {
        console.log(isInViewPortOfOne(ele));
        if (isInViewPortOfOne(ele)) {
          if (!ele.classList.contains("item_animate")) {
            ele.classList.add("item_animate");
          }
        }
      });
    }
  };
  const bindHandleScroll = (event: any) => {
    checkScrollHeightAndLoadAnimation();
  };

  useEffect(() => {
    checkScrollHeightAndLoadAnimation();
    window.addEventListener("scroll", bindHandleScroll);
  }, []);

  return (
    <Box>
      <Container
        sx={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          pt: "7rem",
          pb: { xs: 8, sm: 12 },
        }}
      >
        <HelpStack>
          <HelpH1 text="1. Align Example" />
          <HelpParagraph>
            <div style={{ display: "inline-block", textIndent: "2em" }}>
              Using human dopa decarboxylase
            </div>
            &nbsp; (DDC, PDB ID:{" "}
            <span
              style={{ cursor: "pointer", color: "rgb(56, 116, 203)" }}
              onClick={() => window.open("https://www.rcsb.org/structure/3RBF")}
            >
              3RBF
            </span>
            , Chain A) as a template to search potential DDC enzyme on&nbsp;
            <span style={{ fontStyle: "oblique", fontWeight: "bold" }}>
              Bifidobacterium adolescentis
            </span>{" "}
            genome.
          </HelpParagraph>

          <HelpH2 text="1.1 Steps" marginBottom="0.7rem" />
          <Box
            sx={{
              boxShadow: 0,
              paddingLeft: "2rem",
            }}
          >
            <Image
              src={p1}
              className="item_container"
              style={{
                width: "auto",
                height: "auto",
                maxHeight: "70%",
                maxWidth: "70%",
                opacity: 0,
              }}
              alt="Picture of the author"
            />
          </Box>
          <ImgContainer>
            <Image
              className="item_container"
              src={p2}
              style={{
                width: "auto",
                height: "auto",
                maxHeight: "70%",
                maxWidth: "70%",
                opacity: 0,
              }}
              alt="Picture of the author"
            />
          </ImgContainer>
          <ImgContainer>
            <Image
              className="item_container"
              src={p3}
              style={{
                width: "auto",
                height: "auto",
                maxHeight: "70%",
                maxWidth: "70%",
                opacity: 0,
              }}
              alt="Picture of the author"
            />
          </ImgContainer>

          <ImgContainer>
            <Image
              className="item_container"
              src={p4}
              style={{
                width: "auto",
                height: "auto",
                maxHeight: "70%",
                maxWidth: "70%",
                opacity: 0,
              }}
              alt="Picture of the author"
            />
          </ImgContainer>
        </HelpStack>
        {/* gmps search pipeline  */}
        <HelpStack>
          <HelpH2 text="1.2 Searching pipeline" />
          <HelpParagraph>
            <div
              style={{
                fontWeight: "bold",
                textIndent: "2em",
                display: "inline-block",
              }}
            >
              Step 1. Screening for potential similar structures:
            </div>
            &nbsp;Perform an initial search for potential similar structures
            using Foldseek
            <span style={{ fontSize: "16px" }}>
              {" "}
              (446e46d70ef76f6526aedf3b943c669ab633da5f)
            </span>
            .
          </HelpParagraph>

          <HelpParagraph>
            <div
              style={{
                fontWeight: "bold",
                textIndent: "2em",
                display: "inline-block",
              }}
            >
              Step 2. Ranking structures by structural similarity:
            </div>
            &nbsp;Use US-Align (20240319) to calculate the structural similarity
            (TM-score) between the potential similar structures and the
            template. Structures with the both TM-score greater than 0.5 are
            considered confidently similar and are ranked based on their
            similarity to the template.
          </HelpParagraph>
          <HelpParagraph>
            <div
              style={{
                fontWeight: "bold",
                textIndent: "2em",
                display: "inline-block",
              }}
            >
              Step 3. Sequence similarity calculation:
            </div>
            &nbsp;Use Blastp (2.15.0+) to perform a sequence alignment of the
            top 20 most similar proteins.
          </HelpParagraph>
          <HelpParagraph marginBottom="0.6rem">
            <div
              style={{
                fontWeight: "bold",
                textIndent: "2em",
                display: "inline-block",
              }}
            >
              Step 4. Visualization of the top 20 structures:
            </div>
            &nbsp;Align the top 20 structures with the template using US-align
            and visualize the superposed structures using PyMOL.
          </HelpParagraph>
        </HelpStack>
        {/* gmps search result  */}
        <HelpStack>
          <HelpH2 text="1.3 Searching result"></HelpH2>

          <Button
            component="label"
            role={undefined}
            className="item_container"
            variant="contained"
            tabIndex={-1}
            onClick={() => handleDownloadHelpFile("Align_result.zip")}
            startIcon={<CloudUploadIcon />}
            sx={{ width: "300px", textTransform: "none", textAlign: "center" }}
          >
            Example align result file download
          </Button>
        </HelpStack>

        {/* gmps search result description  */}
        <HelpStack>
          <HelpH3 text="Result file description"></HelpH3>

          <div style={{ paddingLeft: "2rem" }}>
            <Descriptions
              bordered
              items={items}
              column={1}
              className="item_container"
            />
          </div>
        </HelpStack>

        <HelpStack>
          <HelpH2 text="1.4 Local test"></HelpH2>

          <HelpParagraph>
            <div
              style={{
                display: "inline-block",
                textIndent: "2em",
              }}
            >
              The <span style={{ fontWeight: "bold" }}>GMPS pipeline </span>and
              <span style={{ fontWeight: "bold" }}>
                &nbsp;example dataset
              </span>{" "}
              have also been deposited on GitHub
            </div>{" "}
            (
            <span
              style={{
                cursor: "pointer",
                color: "rgb(56, 116, 203)",
              }}
              onClick={() =>
                window.open(
                  "https://github.com/BinhongLiu/Functional-Discovery-of-the-Human-Gut-Microbiome-via-the-Structural-Proteome/tree/main"
                )
              }
            >
              https://github.com/BinhongLiu/Functional-Discovery-of-the-Human-Gut-Microbiome-via-the-Structural-Proteome/tree/main
            </span>
            <span
              style={{
                paddingLeft: "3px",
                paddingRight: "3px",
              }}
            >
              |
            </span>
            <span
              style={{
                cursor: "pointer",
                color: "rgb(56, 116, 203)",
              }}
              onClick={() => window.open("https://github.com/kad-ecoli/GMPS")}
            >
              https://github.com/kad-ecoli/GMPS
            </span>
            )
            <span>
              , enabling users to perform local tests and better understand the
              alignment methodology of the website.
            </span>{" "}
          </HelpParagraph>
        </HelpStack>
        {/* gmps download of gmps database  */}
        <HelpStack>
          <HelpH1 text="2. Database Download" marginTop="0.6rem" />
          <HelpH2 text="2.1 Files download"></HelpH2>
          <HelpParagraph>
            <div
              style={{
                display: "inline-block",
                textIndent: "2em",
              }}
            >
              The bacteria data is named according to species names. The total
              size of the bacteria database (.gz) is approximately 130 GB, which
              expands to about 1.3 TB when fully decompressed. The phage and
              prophage data are separated based on the host species they infect.
              The total size of the phage database is approximately 750 MB,
              while the prophage database is about 2.3 GB (.gz).
            </div>
          </HelpParagraph>

          <HelpParagraph>
            <div
              style={{
                fontWeight: "bold",
                display: "inline-block",
                textIndent: "2em",
              }}
            >
              Structures, sequences, genomes:
            </div>{" "}
            Directly{" "}
            <span
              style={{ cursor: "pointer", color: "rgb(56, 116, 203)" }}
              onClick={() => router.push("download")}
            >
              download
            </span>{" "}
            the GMPS structures from the download interface. We have also
            provided a{" "}
            <span
              style={{ cursor: "pointer", color: "rgb(56, 116, 203)" }}
              onClick={() =>
                window.open(
                  "http://datadryad.org/stash/share/jEoO5KaJgRi-xLp1Rw3_Kakh9AXK0jV_ZMUjLGleBh4"
                )
              }
            >
              DRYAD link
            </span>
            &nbsp;and recommend using it to facilitate bulk download.
          </HelpParagraph>
          <HelpParagraph>
            <div
              style={{
                fontWeight: "bold",
                display: "inline-block",
                textIndent: "2em",
              }}
            >
              Metadata of GMPS protein structures:
            </div>{" "}
            metadata (e.g. functional annotation) of the GMPS structures are
            separately included in the .gz file of each bacterial species. A
            complete metadata for all the GMPS bacterial or phage structures
            could be downloaded from the&nbsp;
            <span
              style={{ cursor: "pointer", color: "rgb(56, 116, 203)" }}
              onClick={() =>
                window.open(
                  "http://datadryad.org/stash/share/jEoO5KaJgRi-xLp1Rw3_Kakh9AXK0jV_ZMUjLGleBh4"
                )
              }
            >
              DRYAD link
            </span>
            .
          </HelpParagraph>
          <HelpParagraph>
            <div
              style={{
                fontWeight: "bold",
                display: "inline-block",
                textIndent: "2em",
              }}
            >
              Metadata of the bacterial and phage genomes for the GMPS
              structures:
            </div>{" "}
            It could also be downloaded from the{" "}
            <span
              style={{ cursor: "pointer", color: "rgb(56, 116, 203)" }}
              onClick={() =>
                window.open(
                  "http://datadryad.org/stash/share/jEoO5KaJgRi-xLp1Rw3_Kakh9AXK0jV_ZMUjLGleBh4"
                )
              }
            >
              DRYAD link
            </span>
            .
          </HelpParagraph>
        </HelpStack>
        {/* Database file description*/}
        <HelpStack>
          <HelpH2 text="2.2 Files information" marginTop="0.6rem"></HelpH2>
          <Box sx={{ borderRadius: "12px" }}>
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                alignItems: "start",
                marginBottom: "1rem",
              }}
            >
              <HelpParagraph>
                <Rate
                  count={1}
                  defaultValue={1}
                  allowClear={false}
                  style={{ marginRight: "7px" }}
                />{" "}
                example 1, bacteria&nbsp;
                <span style={{ fontStyle: "oblique" }}>
                  Bifidobacterium adolescentis
                </span>
              </HelpParagraph>

              <Button
                className="item_container"
                component="label"
                role={undefined}
                variant="text"
                tabIndex={-1}
                startIcon={<CloudUploadIcon />}
                onClick={() =>
                  handleDownloadHelpFile(
                    "BACTERIA_Bifidobacterium_adolescentis.tar.gz"
                  )
                }
                sx={{
                  width: "250px",
                  textTransform: "none",
                  marginTop: "1rem",
                  background: "rgb(247, 250, 253)",
                }}
              >
                Example bacteria file download
              </Button>
            </div>
            {item1s?.map((item) => {
              return (
                <Box key={item.key} sx={{ mb: 1 }}>
                  <HelpParagraphIndent>{item.label}:</HelpParagraphIndent>
                  <HelpParagraphIndent marginTop="3px">
                    {item.children}
                  </HelpParagraphIndent>
                </Box>
              );
            })}
          </Box>

          <div className="item_container">
            <Box
              sx={{
                width: "100%",
                height: "2px",
                borderRadius: "10px",
                background: "#e5e7eb",
              }}
            ></Box>
          </div>

          <Box
            sx={{
              borderRadius: "12px",
            }}
          >
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                alignItems: "left",
                marginBottom: "1rem",
              }}
            >
              <HelpParagraph>
                <Rate
                  count={1}
                  defaultValue={1}
                  allowClear={false}
                  style={{ marginRight: "7px" }}
                />{" "}
                example 2, phage of&nbsp;
                <span style={{ fontStyle: "oblique" }}>
                  Bifidobacterium adolescentis
                </span>
              </HelpParagraph>

              <Button
                component="label"
                role={undefined}
                variant="text"
                tabIndex={-1}
                className="item_container"
                startIcon={<CloudUploadIcon />}
                onClick={() =>
                  handleDownloadHelpFile(
                    "PHAGE_Bifidobacterium_adolescentis.tar.gz"
                  )
                }
                sx={{
                  width: "250px",
                  textTransform: "none",
                  marginTop: "1rem",
                  background: "rgb(247, 250, 253)",
                }}
              >
                Example phage file download
              </Button>
            </div>

            {item2s?.map((item) => {
              return (
                <Box key={item.key} sx={{ mb: 1 }}>
                  <HelpParagraphIndent>{item.label}:</HelpParagraphIndent>
                  <HelpParagraphIndent marginTop="3px">
                    {item.children}
                  </HelpParagraphIndent>
                </Box>
              );
            })}
          </Box>
        </HelpStack>
        <HelpStackIndent>
          <HelpH3 text="Annotation information in the metadata table of GMPS proteins"></HelpH3>
          <CustomizedTables />
        </HelpStackIndent>
      </Container>
    </Box>
  );
}
